﻿Imports System
Imports System.Windows.Forms
Imports VMWorkshop.Domain
Imports AutoMapper

Partial Public Class Demo
    Inherits Form
    Private _vm As DemoViewModel

    Public Sub New()
        InitializeComponent()
        Mapper.CreateMap(Of Product, ProductListView)()
    End Sub

    Sub Demo_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Me._vm = New DemoViewModel(New ProductRepository())
        Me.InitializeProductsGrid()
        Me.UpdateView()
    End Sub

    Private Sub InitializeProductsGrid()
        Me.productsGrid.AutoGenerateColumns = False
        Me.productsGrid.DataSource = Me._vm.Products
        Me.productsGrid.SelectionMode = DataGridViewSelectionMode.FullRowSelect
        Me.productsGrid.ClearSelection()
    End Sub

    Private Sub UpdateView()
        Me.editPanel.Visible = Me._vm.IsEditFormVisible
        Me.updateMsgPanel.Visible = Me._vm.IsUpdateMessageVisible

        Me.txtDescription.Text = Me._vm.SelectedProduct.Description
        Me.txtPrice.Text = Me._vm.SelectedProduct.Price
        Me.txtQuantity.Text = Me._vm.SelectedProduct.QuantityOnHand
        Me.txtReleaseDate.Text = Me._vm.SelectedProduct.ReleaseDate
        Me.txtTitle.Text = Me._vm.SelectedProduct.Title
    End Sub

    Private Sub UpdateModel()
        Me._vm.SelectedProduct.Description = Me.txtDescription.Text
        Me._vm.SelectedProduct.Price = Me.txtPrice.Text
        Me._vm.SelectedProduct.QuantityOnHand = Me.txtQuantity.Text
        Me._vm.SelectedProduct.ReleaseDate = Me.txtReleaseDate.Text
        Me._vm.SelectedProduct.Title = Me.txtTitle.Text
    End Sub

    Private Sub productsGrid_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs) Handles productsGrid.SelectionChanged
        If Me.productsGrid.SelectedRows.Count > 0 Then
            Dim id As String = Me.productsGrid.SelectedRows(0).Cells("ProductId").Value.ToString()
            Me._vm.GetSelectedProduct(id)
            Me.UpdateView()
        End If
    End Sub

    Private Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
        Me.UpdateModel()
        Me._vm.Persist()
        Me.UpdateView()
    End Sub

End Class